package com.tag;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * 使用自定义标签格式化日期
 * @author acer
 *
 */
public class DateFormatTag extends TagSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// 默认日期格式
	public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

	private Date date; // 日期
	private String pattern; // 日期格式，如果不传则为默认格式

	@Override
	public int doStartTag() throws JspException {

		String targetTime = " ";

		if(pattern==null || "".equals(pattern)){
			pattern = DEFAULT_FORMAT;
		}
		
		if (date != null) {
			targetTime = getFormatData(date, pattern);
		}

		try {
			super.pageContext.getOut().write(targetTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}

	public void setPattern(String pattern) {
		this.pattern = pattern;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getPattern() {
		return pattern;
	}

	/**
	 * long型时间戳转日期格式
	 * 
	 * @param l
	 * @param formatStr
	 * @return
	 */
	public static String getFormatData(Date l, String formatStr) {
		String date = new SimpleDateFormat(formatStr).format(l);
		return date;
	}
}
